﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WPF_SFrost
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Trim() == "" || txtPassword.Text.Trim() == "")
            {
                MessageBox.Show("用户名或密码不能为空。");
                txtUserName.Focus();
                return;
            }

            try
            {
                //使用这种语句，会造成SQL注入漏洞，例如在【账号】和【密码】中输入： 1' or '1' = '1
                //string strSQL = string.Format("select * from [User] where UserName='{0}' and Password='{1}'",txtUserName.Text.Trim(), txtPassword.Text.Trim());
                //奇怪，在WF里，必须要给表加上[]中括号
                //补充：错，因为user在MSSQL中为保留字，所以必须加[]号

                //使用@para参数SQL语句，再到cmd中添加参数值，就不会造成SQL注入漏洞
                string sql = "select count(*) from [user] where username = @username and password=@password";
                //SqlCommand cmd = new SqlCommand(sql,conn);
                //cmd.Parameters.AddWithValue("@username", txtUserName.Text.Trim());
                //cmd.Parameters.AddWithValue("@password", txtPassword.Text.Trim());
                //sdr = cmd.ExecuteReader();
                SqlParameter[] parameters =
                {
                    new SqlParameter("@username",SqlDbType.VarChar,50),
                    new SqlParameter("@password",SqlDbType.VarChar,50)
                };
                parameters[0].Value = txtUserName.Text.Trim();
                parameters[1].Value = txtPassword.Text.Trim();
                int n = (int)SqlDbHelper.ExecuteScalar(sql, CommandType.Text, parameters);
                if (n == 1)
                {
                    //MessageBox.Show("登录成功。");
                    UserHelper.username = txtUserName.Text.Trim();
                    UserHelper.password = txtPassword.Text.Trim();
                    Main formMain = new Main();
                    this.Hide();
                    formMain.Show();
                }
                else
                {
                    MessageBox.Show("用户名或密码错误，请重新办理入。","错误提示");
                    txtUserName.Focus();
                    txtUserName.SelectAll();
                }
            }
            catch (Exception eX)
            {
                MessageBox.Show(eX.ToString(),"异常错误");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }
    }
}
